<?php

defined("_ARKN_EXEC") or exit("no no, mr. superman no here");

require_once ROOT_FOLDER . "/php/configs/database_cfg.php";

class Department {
	
	private $db;
	private $isDbConnected;
	private $logger;
	
	public $id;
	public $name;

	public function __construct() {
		$this->logger = Logger::getLogger("Department.php");
		$this->db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
		if($this->db->connect_error)
			throw new Exception("Database connection error");
	}
	
	public function departments() {
		$this->logger->info("Department.departments enter.");
		$deps = NULL;
		$this->logger->info("Preparing statement.");
		if($stmt = $this->db->prepare("select departmentid, name from departments order by departmentid;")) {
			$stmt->execute();
			$stmt->store_result();
			if(!$stmt->errno) {
				$results = $this->bind_result_array($stmt);
				$deps = array();
				$count = 0;
				while($stmt->fetch()) {
					$row = $this->getCopy($results);
					$aux = new Department();
					$aux->id = $results["departmentid"];
					$aux->name = $results["name"];
					$deps[$count++] = $aux;
				}
				$stmt->close();
			} else
				$this->logger->info("Error occured while executing the SQL statement.");
		} else
			$this->logger->info("Error occured while preparing the SQL statement.");
		$this->logger->info("Department.departments exit.");
		return $deps;
	}
	
	function bind_result_array($stmt) {
		$meta = $stmt->result_metadata();
		$results = array();
		while ($field = $meta->fetch_field()) {
			$results[$field->name] = NULL;
			$params[] = &$results[$field->name];
		}
		call_user_func_array(array($stmt, "bind_result"), $params);
		return $results;
	}

	function getCopy($row) {
		return array_map(create_function('$a', 'return $a;'), $row);		
	}
	
	public function __destruct() {
		if($this->db != NULL) {
			$this->db->kill($this->db->thread_id);
			$this->db->close();
		}
	}
}

$department = new Department();
?>